package com.win.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;

@Configuration
@ConfigurationProperties(prefix = AliyunProperties.PREFIX)
public class AliyunProperties {

    public static final String PREFIX = "aliyun";

    private String accessKeyId;

    private String accessKeySecret;

    @NestedConfigurationProperty
    private OSSConfig oss;


    public String putObject(String key, InputStream is) {
        String endpoint = oss.getEndpoint();
        String bucketName = oss.getBucket();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        if (!ossClient.doesBucketExist(bucketName)) {
            System.out.println("Creating bucket " + bucketName + "\n");
            ossClient.createBucket(bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }
        ossClient.putObject(new PutObjectRequest(bucketName, key, is));

        return "https://" + bucketName + "." + endpoint + "/" + key;
    }


    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public OSSConfig getOss() {
        return oss;
    }

    public void setOss(OSSConfig oss) {
        this.oss = oss;
    }

    public static class OSSConfig {
        private String endpoint;
        private String bucket;

        public String getEndpoint() {
            return endpoint;
        }

        public void setEndpoint(String endpoint) {
            this.endpoint = endpoint;
        }

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }


    }

}
